/**
 * 尊敬的用户，你好：页面 JS 面板是高阶用法，一般不建议普通用户使用，如需使用，请确定你具备研发背景，能够自我排查问题。
 * 我们可以用 JS 面板来开发一些定制度高功能，比如：调用API接口，自定义动作执行等等。
 */

export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);
    addStyle();
    const self = this;
    initElement(self);

}


function initElement(self) {
    debugger
    let htmlStr = `
        <div class="month-switch">
            <button id="prevMonth">◀</button>
            <span id="monthDisplay">2025年9月</span>
            <button id="nextMonth">▶</button>
        </div>
        
        <div class="calendar">
            <div class="weekdays">
                <div>周一</div><div>周二</div><div>周三</div><div>周四</div><div>周五</div><div>周六</div><div>周日</div>
            </div>
            <div class="days" id="daysContainer"></div>
        </div>
        
        <div class="stats">
            <h3>月统计</h3>
            <div class="stat-grid">
                <div class="stat-item"><span class="dot color-green"></span> 出勤 0</div>
                <div class="stat-item"><span class="dot color-green"></span> 全勤 0</div>
                <div class="stat-item"><span class="dot color-pink"></span> 缺勤 0</div>
                <div class="stat-item"><span class="dot color-yellow"></span> 迟到 0</div>
                <div class="stat-item"><span class="dot color-orange"></span> 早退 0</div>
                <div class="stat-item"><span class="dot color-orange"></span> 异常 0</div>
                <div class="stat-item"><span class="dot color-pink"></span> 旷工 0</div>
                <div class="stat-item"><span class="dot color-blue"></span> 请假 0</div>
                <div class="stat-item"><span class="dot color-cyan"></span> 打卡 0</div>
            </div>
        </div>
    `;
    let textEle = self.$$("text_hcigsf")
    const targetNode = textEle.$el;
    const config = { childList: true, subtree: true };

    const observer = new MutationObserver((mutationsList, observer) => {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                initData();
                observer.disconnect();
                break;
            }
        }
    });

    observer.observe(targetNode, config);
    textEle.$$setValue(htmlStr);

}

function initData() {

    const daysContainer = document.getElementById("daysContainer");
    const monthDisplay = document.getElementById("monthDisplay");
    // const citySummary = document.getElementById("citySummary");


    const STATUS_COLOR = {
        present: "active",      // 绿色 出勤
        late: "color-yellow",   // 黄色 迟到
        early: "color-orange",  // 橙色 早退
        leave: "color-blue",    // 蓝色 请假
        absent: "color-pink",   // 粉色 旷工/缺勤
        weekend: "inactive"     // 灰色 周末
    };


    const CITIES = ["武汉", "北京"];

    function getRandomStatus(isWeekend) {
        if (isWeekend) return "weekend";
        const rand = Math.random();
        if (rand < 0.7) return "present";
        if (rand < 0.8) return "late";
        if (rand < 0.85) return "early";
        if (rand < 0.9) return "leave";
        return "absent";
    }

    function renderCalendar(year, month) {
        daysContainer.innerHTML = "";

        const stats = {
            present: 0,
            late: 0,
            early: 0,
            leave: 0,
            absent: 0,
            weekend: 0
        };

        const citiesSet = new Set();

        const firstDay = new Date(year, month - 1, 1);
        const startWeekday = (firstDay.getDay() + 6) % 7;
        const totalDays = new Date(year, month, 0).getDate();

        const today = new Date();
        const todayYear = today.getFullYear();
        const todayMonth = today.getMonth() + 1;
        const todayDate = today.getDate();

        const isFutureMonth = year > todayYear || (year === todayYear && month > todayMonth);


        for (let i = 0; i < startWeekday; i++) {
            const blank = document.createElement("div");
            blank.className = "day";
            const circle = document.createElement("div");
            circle.className = "circle";
            blank.appendChild(circle);
            daysContainer.appendChild(blank);
        }


        for (let d = 1; d <= totalDays; d++) {
            const dayDiv = document.createElement("div");
            dayDiv.className = "day";

            const circle = document.createElement("div");
            circle.classList.add("circle");

            const dayOfWeek = (startWeekday + d - 1) % 7;
            const isWeekend = dayOfWeek >= 5;
            let status = "present";

            if (isFutureMonth || (year === todayYear && month === todayMonth && d > todayDate)) {
                status = "inactive";
            } else if (isWeekend) {
                status = "weekend";
            } else {
                status = getRandomStatus(isWeekend);
            }

            if (status === "weekend") circle.classList.add(STATUS_COLOR.weekend);
            else circle.classList.add(STATUS_COLOR[status]);

            circle.textContent = d;

            const location = document.createElement("div");

            if (status !== "weekend" && status !== "inactive" && !(year === todayYear && month === todayMonth && d > todayDate)) {
                const city = CITIES[Math.floor(Math.random() * CITIES.length)];
                location.textContent = city;
                location.className = "location";
                citiesSet.add(city);
            }

            if (status === "inactive") {
                circle.style.backgroundColor = "#fff";
                circle.style.color = "#223355";
                circle.style.border = "1px solid #ddd";
            }

            dayDiv.appendChild(circle);
            dayDiv.appendChild(location);
            daysContainer.appendChild(dayDiv);

            if (stats[status] !== undefined) stats[status]++;
        }


        document.querySelector(".stat-item:nth-child(1)").innerHTML = `<span class="dot color-white"></span> 出勤 ${stats.present}`;
        document.querySelector(".stat-item:nth-child(2)").innerHTML = `<span class="dot color-green"></span> 全勤 ${stats.present - (stats.late + stats.early + stats.absent)}`;
        document.querySelector(".stat-item:nth-child(3)").innerHTML = `<span class="dot color-pink"></span> 缺勤 ${stats.absent}`;
        document.querySelector(".stat-item:nth-child(4)").innerHTML = `<span class="dot color-yellow"></span> 迟到 ${stats.late}`;
        document.querySelector(".stat-item:nth-child(5)").innerHTML = `<span class="dot color-orange"></span> 早退 ${stats.early}`;
        document.querySelector(".stat-item:nth-child(6)").innerHTML = `<span class="dot color-orange"></span> 异常 ${stats.late + stats.early + stats.absent}`;
        document.querySelector(".stat-item:nth-child(7)").innerHTML = `<span class="dot color-pink"></span> 旷工 ${stats.absent}`;
        document.querySelector(".stat-item:nth-child(8)").innerHTML = `<span class="dot color-blue"></span> 请假 ${stats.leave}`;
        document.querySelector(".stat-item:nth-child(9)").innerHTML = `<span class="dot color-cyan"></span> 打卡 ${stats.present + stats.late + stats.early}`;

    }
    const currentDate = new Date();

    let currentYear = currentDate.getFullYear();

    let currentMonth = currentDate.getMonth() + 1;

    monthDisplay.textContent = `${currentYear}年${currentMonth.toString().padStart(2, '0')}月`;
    renderCalendar(currentYear, currentMonth);

    document.getElementById("prevMonth").addEventListener("click", () => {
        currentMonth--;
        if (currentMonth === 0) {
            currentMonth = 12;
            currentYear--;
        }
        monthDisplay.textContent = `${currentYear}年${currentMonth.toString().padStart(2, '0')}月`;
        renderCalendar(currentYear, currentMonth);
    });

    document.getElementById("nextMonth").addEventListener("click", () => {
        currentMonth++;
        if (currentMonth === 13) {
            currentMonth = 1;
            currentYear++;
        }
        monthDisplay.textContent = `${currentYear}年${currentMonth.toString().padStart(2, '0')}月`;
        renderCalendar(currentYear, currentMonth);
    });
}


function addStyle() {
    const css = `
        .month-switch {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #fff;
            padding: 10px 16px;
            border-bottom: 1px solid #eee;
        }

        .month-switch button {
            background: none;
            border: none;
            font-size: 18px;
            color: #008aff;
        }

        .month-switch span {
            font-size: 16px;
            font-weight: 500;
        }

        .calendar {
            background: #fff;
            text-align: center;
            padding-bottom: 10px;
        }

        .calendar .weekdays {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            border-bottom: 1px solid #eee;
            padding: 8px 0;
            color: #0099ff;
            font-weight: 500;
            font-size: 14px;
        }

        .calendar .days {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 10px;
            padding: 10px 20px;
            text-align: center;
        }

        .day {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-size: 14px;
            color: #444;
        }

        .day .circle {
            width: 42px;
            height: 42px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            margin-bottom: 4px;
        }

        .active {
            background: #0dc262;
        }
        .inactive {
            background: #e5e5e5;
            color: #999;
        }
        .color-pink { background: #e91e63; }
        .color-yellow { background: #fbc02d; }
        .color-orange { background: #ff9800; }
        .color-blue { background: #2196f3; }
        .color-cyan { background: #00bcd4; }
        .color-green { background: #009688; }
        .color-white { background: #fff; }

        .location {
            font-size: 12px;
            color: #777;
        }

        .stats {
            margin-top: 10px;
            background: #fff;
            padding: 10px;
            font-size: 14px;
        }

        .stats h3 {
            font-size: 16px;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .stat-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            border-top: 1px solid #eee;
            border-left: 1px solid #eee;
        }

        .stat-item {
            border-right: 1px solid #eee;
            border-bottom: 1px solid #eee;
            padding: 10px;
            text-align: center;
        }

        .stat-item .dot {
            display: inline-block;
            width: 8px;
            height: 8px;
            border: 1px solid #E9ECF2;
            border-radius: 50%;
            margin-right: 4px;
        }

        .summary {
            padding: 10px;
            background: #fff;
            font-size: 14px;
            border-top: 1px solid #eee;
        }

        .summary span {
            color: #00aaff;
        }
        .detail-card {
            background: #fff;
            margin-top: 10px;
            padding: 12px 16px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            font-size: 14px;
            animation: fadeIn 0.3s ease;
        }
        .detail-header {
            font-weight: 600;
            color: #008aff;
            margin-bottom: 6px;
        }
        .detail-body p {
            margin: 4px 0;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @media (max-width: 400px) {
            .day .circle {
                width: 36px;
                height: 36px;
            }
        }
    `;
    const style = document.createElement("style");
    style.id = "lawEnforcementOversight";
    style.textContent = css.trim();

    const existingStyle = document.head.querySelector("style#lawEnforcementOversight");
    if (existingStyle) {
        existingStyle.textContent = css.trim();
    } else {
        document.head.appendChild(style);
    }
}
